package com.youboy.wechatapi.utils.wechat;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Map;

import net.sf.json.JSONObject;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.codehaus.jackson.JsonParseException;
import org.codehaus.jackson.map.JsonMappingException;

import com.youboy.wechatapi.domain.pojo.Button;
import com.youboy.wechatapi.domain.pojo.CommonButton;
import com.youboy.wechatapi.domain.pojo.ComplexButton;
import com.youboy.wechatapi.domain.pojo.Menu;
import com.youboy.wechatapi.utils.http.HttpClient;
import com.youboy.wechatapi.utils.json.JacksonMapper;
  
/** 
 * 菜单管理器类 
 *  
 */  
public class MenuManager {  
	
    private static Logger log = Logger.getLogger(MenuManager.class);
 
    /** 
     * 组装菜单数据 
     *  
     * @return 
     */  
    private static Menu getMenu() {  
    	String wechatUrl = "http://wechatapi.youboy.com";
    	String url = null;
    	try {
			url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx38b4f62566498991"
					+ "&redirect_uri="+URLEncoder.encode(wechatUrl+"/bind/index", "utf-8")
					+ "&response_type=code"
					+ "&scope=snsapi_base&state=1#wechat_redirect";
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
    	
        CommonButton btn10 = new CommonButton();  
        btn10.setName("我的商铺");  
        btn10.setType("view");  
        btn10.setUrl(url);
        btn10.setKey("10");  
  
  
  
        ComplexButton mainBtn1 = new ComplexButton();  
        mainBtn1.setName("我的商铺");  
        mainBtn1.setSub_button(new CommonButton[] { btn10});  
  
        CommonButton btn20 = new CommonButton();  
        btn20.setName("我要搜索");  
        btn20.setType("view");  
        btn20.setUrl("http://m.youboy.com");
        btn20.setKey("20");  
  
        CommonButton btn30 = new CommonButton();  
        btn30.setName("VIP展位");  
        btn30.setType("view");  
        //btn30.setUrl("http://wap.youboy.com/?host=www.youboy.com&src=http%3A%2F%2Fnews.youboy.com%2F");
        String shopUrl = null;
        try {
        	String uri = URLEncoder.encode(wechatUrl+"/vip/show", "utf-8");
        	shopUrl = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx38b4f62566498991"
					+ "&redirect_uri="+URLEncoder.encode(wechatUrl+"/help/wechatCallBack?redirect_url="+uri, "utf-8")
					+ "&response_type=code"
					+ "&scope=snsapi_base&state=1#wechat_redirect";
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
        //btn30.setUrl(wechatUrl+"/vip/show");//
        btn30.setUrl(shopUrl);
        btn30.setKey("30");  
        
  
        /** 
         * 每个一级菜单都有二级菜单项<br> 
         *  
         * 在某个一级菜单下没有二级菜单的情况，menu该如何定义呢？<br> 
         * 比如，第三个一级菜单项不是“更多体验”，而直接是“幽默笑话”，那么menu应该这样定义：<br> 
         * menu.setButton(new Button[] { mainBtn1, mainBtn2, btn33 }); 
         */  
        Menu menu = new Menu();  
        menu.setButton(new Button[] { btn10, btn20, btn30 });  
  
        return menu;  
    }  
    
    
    public static void deleteMenu(String token){
    	String url="https://api.weixin.qq.com/cgi-bin/menu/delete?access_token=ACCESS_TOKEN";
    	 // 拼装创建菜单的url  
        String deleteUrl = url.replace("ACCESS_TOKEN", token); 
        JSONObject  jsonObject = WeixinUtil.httpsRequest(deleteUrl, "GET", "");
        if (null != jsonObject) {  
            if (0 != jsonObject.getInt("errcode")) {  
                //jsonObject.getInt("errcode"); 
                log.error("删除菜单失败 errcode:{}"+jsonObject.getInt("errcode")+" errmsg:{}"+jsonObject.getString("errmsg"));  
            }  
        }  
    }
    
    public static void createMenu(String token){
    	   int result = createMenu(getMenu(), token);  
    	   
           // 判断菜单创建结果  
           if (0 == result)  
               log.info("菜单创建成功！");  
           else  
               log.info("菜单创建失败，错误码：" + result);  
    }
    
    /** 
     * 创建菜单 
     *  
     * @param menu 菜单实例 
     * @param accessToken 有效的access_token 
     * @return 0表示成功，其他值表示失败 
     */  
    @SuppressWarnings("unchecked")
	public static int createMenu(Menu menu, String accessToken) {  
        int result = 0;  
      
        // 拼装创建菜单的url  
        
        String url = WechatApi.MENU_CREATE_URL.replace("ACCESS_TOKEN", accessToken);  
        // 将菜单对象转换成json字符串  
        String jsonMenu = JSONObject.fromObject(menu).toString();   
        // 调用接口创建菜单  
        String json = null;
		
		try {
			json = HttpClient.httpsRequest(url, jsonMenu);
		} catch (Exception e) {
			e.printStackTrace();
		}
	
        if(StringUtils.isNotBlank(json)){
        	Map<String, Object> value = null;
			try {
				value = JacksonMapper.getInstance().readValue(json, Map.class);
			} catch (JsonParseException e) {
				e.printStackTrace();
			} catch (JsonMappingException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
        	Integer errcode = Integer.valueOf(value.get("errcode").toString());
        	 if (0 != errcode) {  
                 result = errcode; 
                 log.error("创建菜单失败 errcode:{"+errcode+"} errmsg:{"+value.get("errmsg")+"}");  
             }  
        }
       /* JSONObject jsonObject = WeixinUtil.httpsRequest(url, "POST", jsonMenu); 
      
        if (null != jsonObject) {  
            if (0 != jsonObject.getInt("errcode")) {  
                result = jsonObject.getInt("errcode"); 
                log.error("创建菜单失败 errcode:{}"+jsonObject.getInt("errcode")+" errmsg:{}"+jsonObject.getString("errmsg"));  
            }  
        }  */
      
        return result;  
    }  
    
    public static void main(String[] args) {
    	String accessToken = WeixinUtil.getAccessToken(WechatApi.APPID, WechatApi.SECRET).getToken();
    	System.out.println(accessToken);
    	createMenu(accessToken);
	}
}  
